package com.valveinspectionsys.routing.activity;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.gridview.ImageSwitcherActivity;
import com.valveinspectionsys.povo.DeviceItem;
import com.valveinspectionsys.povo.DeviceVo;
import com.valveinspectionsys.routing.BaseAdapter.DeviceRoutingCheckAdapter;
import com.valveinspectionsys.routing.db.DeviceRoutingDao;
import com.valveinspectionsys.util.CHexConver;
import com.valveinspectionsys.util.SharedPreferenceUtil;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 巡检
 * @author King
 *
 */
public class DeviceRoutingCheck extends Activity implements OnClickListener{
    
    public static final int REQUEST_CODE_PAIZHAO=1;
    
    public ListView  listview;
    
    public DeviceRoutingCheckAdapter adapter;
    
    public Button button;//保存
    
    public Button button1;//拍照
    
    public Button button2;//读卡
    
    public TextView textinfo;//统计信息
    
   public List<Integer> info =new ArrayList<Integer>();
    
    public List<DeviceItem> item =new ArrayList<DeviceItem>();//当前设备册的
    
    public DeviceRoutingDao  dao;
    
    public SharedPreferenceUtil  sp;
    
    public long time;
    public boolean isStop=false;
    private String rfidNumber;
    
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    
    public DeviceVo  device;//一个设备信息
      
    public TextView textview2;//设备编号
    public TextView textview3;//设备地址
    public TextView textview4;//公称口径
    public TextView textview5;//设备类型

    public EditText  edit;//备注
    
    
    public int total=0;
    public int nocopytotal=0;
    public boolean isSave=false;
    public String devicelistid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.device_routing_check_rfid);
	devicelistid=getIntent().getStringExtra("devicelistid");
	sp=new SharedPreferenceUtil(this);
	dao=new DeviceRoutingDao(this, sp.getValue(XmlNameHelper.SqliteName));
	textinfo=(TextView)findViewById(R.id.device_routing_check_rfid_info);
	textview2=(TextView)findViewById(R.id.device_routing_check_rfid_number);
	textview3=(TextView)findViewById(R.id.device_routing_check_rfid_adds);
	
	textview4=(TextView)findViewById(R.id.device_routing_check_rfid_devicecaliber);
	textview5=(TextView)findViewById(R.id.device_routing_check_rfid_devicetype);

	edit=(EditText)findViewById(R.id.device_routing_check_rfid_remark);
	mAdapter = NfcAdapter.getDefaultAdapter(DeviceRoutingCheck.this);
	mPendingIntent = PendingIntent.getActivity(DeviceRoutingCheck.this, 0, new Intent(DeviceRoutingCheck.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
	try {
	    ndef.addDataType("*/*");
	    mFilters = new IntentFilter[] { ndef, };
	    mTechLists = new String[][] { new String[] { NfcV.class.getName() }, new String[] { MifareClassic.class.getName() } };

	} catch (MalformedMimeTypeException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	button=(Button)findViewById(R.id.device_routing_check_rfid_save);
	button1=(Button)findViewById(R.id.device_routing_check_rfid_tag);
	button2=(Button)findViewById(R.id.device_routing_check_rfid_paizhao);
	button.setOnClickListener(this);
	button1.setOnClickListener(this);
	button2.setOnClickListener(this);
	
	listview=(ListView)findViewById(R.id.device_routing_check_rfid_listview);
	item=new ArrayList<DeviceItem>();
	info=new ArrayList<Integer>();
        
	adapter=new DeviceRoutingCheckAdapter(item, info, this);
	listview.setAdapter(adapter);
	
	
    }

  
    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.device_routing_check_rfid_save:
	    if(device==null){
		 Toast.makeText(DeviceRoutingCheck.this, "请先读卡确认此设备！", Toast.LENGTH_SHORT).show();
		return;
	    }
	     if(isSelectAll(adapter.getInfo())){
		 isSave=true;
		     Intent intent=new Intent(DeviceRoutingCheck.this, ImageSwitcherActivity.class);
		     intent.putExtra("otherid", device.getDeviceId());
		     intent.putExtra("status", "1");
		     intent.putExtra("devicelistid", device.getDeviceListId());
		     startActivityForResult(intent, REQUEST_CODE_PAIZHAO);
	     }else{
		 Toast.makeText(DeviceRoutingCheck.this, "请检查所有巡检项目！", Toast.LENGTH_SHORT).show();
	     }
	    break;
	case R.id.device_routing_check_rfid_tag:
	        if(isStop){
	            return;
	        }
	        Toast.makeText(DeviceRoutingCheck.this, "正在读卡中，请将终端靠近标签", Toast.LENGTH_SHORT).show();
	        time=System.currentTimeMillis();
	        isStop=true;
	        rfidNumber="";
	        new Thread(){

		    @Override
		    public void run() {
			while(isStop){
			     if(!TextUtils.isEmpty(rfidNumber)){
				 Message msg=myHandler.obtainMessage();
				 msg.what=1;
				 myHandler.sendMessage(msg);
				 isStop=false;
			     }
			     if(System.currentTimeMillis()-time>10000){
				 Message msg=myHandler.obtainMessage();
				 msg.what=2;
				 myHandler.sendMessage(msg);
				 isStop=false;
			     }
			     try {
				Thread.sleep(300);
			    } catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			    }
			     
			}
			super.run();
		    }
	            
	        }.start();
	    break;
	case R.id.device_routing_check_rfid_paizhao:
	    if(device==null){
		 Toast.makeText(DeviceRoutingCheck.this, "请先读卡确认此设备！", Toast.LENGTH_SHORT).show();
		return;
	    }
	    Intent intent=new Intent(DeviceRoutingCheck.this, ImageSwitcherActivity.class);
	     intent.putExtra("otherid", device.getDeviceId());
	     intent.putExtra("status", "1");
	     intent.putExtra("devicelistid", device.getDeviceListId());
	     startActivityForResult(intent, REQUEST_CODE_PAIZHAO);
	    break;
	default:
	    break;
	}
	
    }

    
    public List<Integer> analyze(String infos){
	
	info.clear();
	if(!TextUtils.isEmpty(infos)&&infos.indexOf(",")>0){
	    String[] str=infos.split(",");
		
		for(int i=0;i<str.length;i++){
		    info.add(Integer.parseInt(str[i]));
		}
	}
	
	if(info.size()==0){
	    for(int i=0;i<item.size();i++){
		info.add(0);
	    }
	}
	return null;
	
    }
    
    
    @Override
    protected void onPause() {

	mAdapter.disableForegroundDispatch(this);

	super.onPause();
    }

    @Override
    protected void onResume() {
	mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

	super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
	if (!isStop) {
	    return;
	}

	if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
	    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	    for (String tech : tagFromIntent.getTechList()) {
		System.out.println(tech);
	    }
	    time = System.currentTimeMillis();
	    MifareClassic mf = MifareClassic.get(tagFromIntent);
	    if (mf != null) {

		boolean auth = false;
		try {
		    mf.connect();
		    auth = mf.authenticateSectorWithKeyA(0, MifareClassic.KEY_DEFAULT);// 获取第一个扇区权限
		    if (auth) {
			byte[] date = mf.readBlock(0);// 读取block 0
			rfidNumber = CHexConver.bytesToHexStrings(date);
			Message msg = myHandler.obtainMessage();
			msg.what = 1;
			msg.obj = rfidNumber;
			myHandler.sendMessage(msg);
		    }

		} catch (IOException e) {

		    e.printStackTrace();
		} finally {
		    try {
			mf.close();
		    } catch (IOException e) {

			e.printStackTrace();
		    }
		}

	    }
	    NfcV nf = NfcV.get(tagFromIntent);
	    if (nf != null) {
		rfidNumber = CHexConver.bytesToHexStrings(nf.getTag().getId());
		Message msg = myHandler.obtainMessage();
		msg.what = 1;
		msg.obj = rfidNumber;
		myHandler.sendMessage(msg);
	    }

	}

	super.onNewIntent(intent);
    }

     Handler myHandler=new Handler(){

	@Override
	public void handleMessage(Message msg) {
	    if(msg.what==1){
		 DeviceVo dev=dao.queryRfidDevice(rfidNumber, null, devicelistid);
		 if(dev==null){
		     Toast.makeText(DeviceRoutingCheck.this, "此标签未绑定设备", Toast.LENGTH_SHORT).show();
		     return;
		 }else{
		    
		     if(device!=null){
			 
			   if(!device.getDeviceListId().equals(dev.getDeviceListId())){
			       item=dao.queryItems(dev.getDeviceListdeviceitem());
			       total=dao.queryAllDeviceTotal(dev.getDeviceListId());
			       nocopytotal=dao.queryNoCopyDeviceTotal(dev.getDeviceListId());
			       textinfo.setText("设备册总数:"+total+", 未巡检数:"+nocopytotal);
			   }
		     }else{
			      total=dao.queryAllDeviceTotal(dev.getDeviceListId());
			       nocopytotal=dao.queryNoCopyDeviceTotal(dev.getDeviceListId());
			      String str="设备册总数:"+total+", 未巡检数:"+nocopytotal;
			      System.out.println(textinfo==null);
			       textinfo.setText(str);
			       item=dao.queryItems(dev.getDeviceListdeviceitem());
		     }
		     analyze(dev.getCopydata());
		     device=dev;
		     edit.setText(device.getRemark());
		      initData();
		     adapter.setInfo(info);
		     adapter.setItem(item);
		     adapter.notifyDataSetChanged();
		 }
	    }else if(msg.what==2){
		Toast.makeText(DeviceRoutingCheck.this, "读卡超时", Toast.LENGTH_SHORT).show();
	    }
	    super.handleMessage(msg);
	}
	 
     };
    
     public void initData(){
	  textview2.setText(device.getDeviceNumber());
	  textview3.setText(device.getDeviceAdds());
	  textview3.setSelected(true);
	  textview4.setText(device.getDeviceCaliber());
	  textview5.setText(device.getDeviceType());
	
     }
     
     //检测所巡检项目是否选择完毕
     public boolean isSelectAll(List<Integer> list){
	 boolean b=true;
	 
	 for(int i=0;i<list.size();i++){
	   
	     if(list.get(i)==0){
		 return false;
	     }
	 }
	return b;
	 
     }
     
     public String checkdata(List<Integer> list){
	 String str="";
	 for(int i=0;i<list.size();i++){
	     str=str+list.get(i)+",";
	 }
	return str.substring(0, str.length()-1);
     }
     
     
     
    @Override
    protected void onDestroy() {
	dao.close();
	super.onDestroy();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if(requestCode==REQUEST_CODE_PAIZHAO){
		if(resultCode==RESULT_OK){
		    if(isSave){
			       boolean b=dao.insertDeviceData(device.getDeviceId(), checkdata(adapter.getInfo()), "0",edit.getEditableText().toString(),devicelistid);
				 if(b){
				     Toast.makeText(DeviceRoutingCheck.this, "添加成功", Toast.LENGTH_SHORT).show();
				 }else{
				     Toast.makeText(DeviceRoutingCheck.this, "添加失败", Toast.LENGTH_SHORT).show();
				 }	
				  isSave=false;
		    }
		  
		}else if(requestCode==RESULT_CANCELED){
		    if(!isSave){
			return;
		    }
		    Toast.makeText(DeviceRoutingCheck.this, "你没有拍照不会保存数据", Toast.LENGTH_SHORT).show();
		}
	    }
	super.onActivityResult(requestCode, resultCode, data);
}

    
    
}
